<?php

namespace App\Http\Controllers\EasyWechat;

use App\Http\Controllers\Controller;
use App\Service\EasyWechat\MiniClientService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class WxMiniController extends Controller
{
    /**
     * 获取微信小程序的openid
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getOpenid(Request $request): JsonResponse
    {
        try {
            // 云调用
            if ($request->input('is_cloud','0') == 1) {
                $openid = $request->header('x-wx-openid', '');
                if ($openid) {
                    return $this->OkJson(['openid' => $openid]);
                }
            }
            $request->validate([
                'code'  => 'required',
            ]);
            $params = $request->only(['code']);
            $miniClientService = new MiniClientService();
            $userInfo          = $miniClientService->getUserInfo($params['code']);
            return $this->OkJson($userInfo);
        } catch (Exception $e) {
            return $this->ErrJson($e->getMessage());
        }
    }

    /**
     * 处理服务端消息
     *
     * @param Request $request
     * @return JsonResponse|ResponseInterface
     */
    public function server(Request $request): JsonResponse|ResponseInterface
    {
        $params = $request->input();
        Log::info("[微信小程序服务端请求数据]", $params);

        try {
            $miniClientService = new MiniClientService();
            $server            = $miniClientService->getServer();
            // token验证
            if ($request->isMethod('get')) {
                return $server->serve();
            }
            try {
                $message          = $server->getRequestMessage()->toArray();  // 原始消息
                $decryptedMessage = $server->getDecryptedMessage()->toArray();// 解密消息
                Log::info("[微信小程序服务端原始消息]", $message);
                Log::info("[微信小程序服务端解密消息]", $decryptedMessage);
            } catch (Throwable $e) {
                Log::error("[微信小程序服务端处理失败]" . $e->getMessage());
            }

            return $server->serve();
        } catch (Exception $e) {
            return $this->ErrJson($e->getMessage());
        }

    }
}
